<?php

namespace app\model;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Model;
use think\model\concern\SoftDelete;
use think\Paginator;

class BaseModel extends Model
{
    use SoftDelete;
    protected $deleteTime='deleted_at';
    // 设置当前模型主键
    protected $pk = 'id';

    protected $autoWriteTimestamp = 'datetime';
    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    /**
     *  添加/修改数据
     * @param $params
     * @return mixed
     */
    public static function edit($params)
    {
        if (empty($params['id'])) {
            $data = self::create($params);
            return $data->id;
        }
        self::update($params);
        return $params['id'];
    }

    /**
     * 根据id获取数据
     * @param $id
     * @param $fields
     * @return BaseModel|array|mixed|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getInfoById($id, $fields = '*')
    {
        return self::where(['id' => $id])->field($fields)->find();
    }

    /**
     * 获取分页数据
     * @param array $where
     * @param string $fields
     * @param string $order
     * @return Paginator
     * @throws DbException
     */
    public static function getPagingDataByWhere(array $where = [], string $fields = '*', string $order = 'id desc'): Paginator
    {
        $params = Request::param();
        $limit = $params['limit'] ?? 10;
        return self::where($where)->field($fields)->order($order)->paginate($limit);
    }

    /**
     * 获取所有数据
     * @param array $where
     * @param string $fields
     * @param string $order
     * @return BaseModel[]|array|\think\Collection
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public static function getDataByWhere(array $where = [], string $fields = '*', string $order = 'id asc')
    {
        return self::where($where)->field($fields)->order($order)->select();
    }

    /**
     * 根据条件获取一条数据
     * @param array $where
     * @param string $fields
     * @return BaseModel|array|mixed|Model|null
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public static function getInfoByWhere(array $where, string $fields = '*')
    {
        return self::where($where)->field($fields)->find();
    }

}